<template>
  <view class="page">
    <uni-nav-bar
      @clickLeft="backPrev"
      style="position: relative;"
      statusBar="true"
      leftIcon="left"
      leftText="询底价"
      :leftWidth="200"
    />
    <view class="top">
      <view class="num">
        已有<view class="color-num">{{ basePrice.ask_price_num }}</view>人完成询价
      </view>
      <view class="tips">{{ basePrice.ask_price_summary }}</view>
    </view>

    <view class="car-info">
      <view class="left">
        <img :src="basePrice.car_style.cover" alt="" />
      </view>
      <view class="middle">
        <view class="title">
          <view class="name">{{ basePrice.car_style.name }}</view>
          <view class="cheap" v-if="basePrice.car_style.discount_price">
            <view class="cheap-cont">{{ basePrice.car_style.discount_price }}</view>
            <view class="jiantou"></view>
          </view>
        </view>
        <view class="price">
          指导价：{{ basePrice.car_style.guide_price ? basePrice.car_style.guide_price : '' }}
        </view>
      </view>
      <view class="right"></view>
    </view>

    <!-- <form @submit="formClick" :clueComponentId="clueComponentId" :conversionTarget="conversionTarget"> -->
    <view class="select-item">
      <view class="item">
        <view class="left">购车城市</view>
        <view class="middle">
          <picker
            title="选择城市"
            mode="multiSelector"
            range-key="name"
            :range="regionList"
            :value="provinceCityIndex"
            mask-style="background: #000;"
            @change="regionListChange"
            @columnchange="regionListColumnchange"
          >
            <view class="picker-box">
              {{ provincename ? provincename : '' }}{{ cityname ? cityname : '' }}
            </view>
          </picker>
        </view>
        <view class="right">
          <img src="../../static/image/right.png" alt="" />
        </view>
      </view>
      <view class="item" v-if="basePrice.dea_is_show" @click="showModal">
        <view class="left">经销商</view>
        <view class="middle">{{ dealerName }}</view>
        <view class="right">
          <img src="../../static/image/right.png" alt="" />
        </view>
      </view>
      <view class="item" v-if="!isEmpower">
        <view class="left">手机号</view>
        <input
          name="input"
          class="middle"
          placeholder="请输入手机号"
          placeholder-style="color:#BEC0C4"
          v-model="phone"
          maxlength="11"
          type="text"
          :clueType="clueType"
          @input="inputChange"
        />
        <view class="right" v-show="phone === ''">
          <button
            class="btn"
            open-type="getPhoneNumber"
            @getphonenumber="onGetPhoneNumbers"
          >获取手机号码</button>
        </view>
      </view>
      <view class="item" v-if="!isShow">
        <view class="left">验证码</view>
        <input
          class="middle"
          type="number"
          v-model="sms_code"
          placeholder="请输入验证码"
          placeholder-style="color:#BEC0C4"
        />
        <view class="right">
          <button class="btn" @click="getSMS" v-if="!isSMS">获取验证码</button>
          <button class="btn" @click="getSMS" v-if="isSMS">{{ countdown }}s</button>
        </view>
      </view>
    </view>

    <view class="btn-box">
		<button
          class="btn-price"
          v-if="isEmpower"
          open-type="getPhoneNumber"
          @getphonenumber="onGetPhoneNumber"
        >
          授权手机号查询成交底价
        </button>
      	<button class="btn-price" v-else @click="formClick">立即询价</button>
		<view class="tips-text">提交信息后可获取最新低价提交即视为同意
			<view style="color:#3075FE" @click="jumpAgreement">《隐私政策》</view>
		</view>
    </view>
    <!-- </form> -->

    <uni-popup ref="popup" mask-background-color="rgba(0,0,0,.4)" safe-area="true">
      <view class="dea-box">
        <view class="cancel-title">
          <view class="cancel" @click="closeModal">取消</view>
          <view class="title">选择经销商</view>
        </view>
        <view class="list-box">
          <view
            class="list-item"
            v-for="item in dealerList"
            :key="item.hid"
            @click="selectDealer(item)"
          >
            <view class="title">{{ item.name }}</view>
            <view class="address">
              <view class="distance" v-if="item.distance !== ''">
                {{ item.distance }} | {{ item.address }}
              </view>
              <view class="distance" v-else>
                {{ item.address }}
              </view>
            </view>
            <uni-icons
              v-show="item.isSelected == 1"
              class="icon"
              type="checkmarkempty"
              size="20"
            ></uni-icons>
          </view>
        </view>
      </view>
    </uni-popup>

    <uni-popup type="center" ref="modalPopup" :mask-click="false">
      <view class="modal">
        <view class="title">温馨提示</view>
        <view class="content">提交成功，我们会尽快与您联系！</view>
        <view class="btn" @click="jumpHome">知道了</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
const Api = require('../../utils/api.js');
const request = require('../../utils/request.js');

import { buryReport } from '../../utils/buryReport.js';
import { deliverClickCallback } from '../../utils/deliverClickCallback.js';

export default {
  data() {
    return {
      carData: {},
      basePrice: {},
      newProvinceCityList: [],
      regionList: [],
      provinceCityIndex: [0, 0],
      phone: '',
      province_id: '',
      city_id: '',
      carId: '',
      loc_lng: '',
      loc_lat: '',
      dealerName: '请选择意向经销商',
      dealerList: [],
      code: '',
      countdown: 60,
      timeClock: null,
      isSMS: false,
      isShow: true,
	  isLocation: false,
      isEmpower: true,
      isClick: false,
      sms_code: '',
      cityName: '',
      provincenName: '',
      dea_is_show: null,
      carHid: '',
      mount_log_hid: '',
      pages: '', // 页面地址
      pageParams: '', // 页面参数
      log_detail_hid: '',
      page_session_id: '',
      hide: 1,
      // clueComponentId:'4844775d58a1524fc15ec11f94136ac7',//极律
      clueComponentId: '40279492fe627efaab93b9b0c42e0bcf', // 这里填写在留资分发配置后台创建的配置 ID
      conversionTarget: 1,
      clueType: 1,
      text: '',
      phone_sign: '',
      submitType: '',
      reqArgs: {},
      isDots: false,
      appIdNum: ''
    };
  },
  computed: {
    provincename() {
      if (!this.isLocation) {
        return '请选择购车城市';
      } else if (
        this.regionList[0] &&
        this.regionList[0][this.provinceCityIndex[0]]
      ) {
        return this.regionList[0][this.provinceCityIndex[0]].name;
      }
      return '';
    },
    cityname() {
      if (!this.isLocation) {
        return '';
      } else if (
        this.regionList[1] &&
        this.regionList[1][this.provinceCityIndex[1]]
      ) {
        return this.regionList[1][this.provinceCityIndex[1]].name;
      } else if (this.provincename === '北京市') {
        return '北京市';
      } else if (this.provincename === '天津市') {
        return '天津市';
      }
      return '';
    }
  },

  async onLoad(options) {
    // 更换线索组件id
    const accountInfo = wx.getAppBaseInfo();
    this.appIdNum = accountInfo.appIdNum;

    this.carHid = JSON.parse(decodeURIComponent(options.val));
    this.reqArgs = options.reqArgs
      ? JSON.parse(decodeURIComponent(options.reqArgs))
      : '';
    this.getBasePrice();
    this.onGetLocationEvent();

    this.phone = uni.getStorageSync('empower_phone') || '';
    this.phone_sign = uni.getStorageSync('phone_sign') || '';

    if (this.phone !== '') {
		// this.isShow = true;
      	this.isEmpower = false;
    }
    // 广告访问页面数据上报
    deliverClickCallback('page_view', this.reqArgs);
  },
  async onShow() {},
  async onHide() {
    this.hide = 0;
  },

  methods: {
    backPrev() {
      uni.navigateBack({
        delta: 1
      });
    },

    // 获取经纬度
    onGetLocationEvent() {
      let _this = this;
      // 用户授权经纬度
      return new Promise((resolve, reject) => {
        wx.getFuzzyLocation({
          success(res) {
            // console.log(res, '经纬度');
            _this.loc_lng = res.longitude;
            _this.loc_lat = res.latitude;
            _this.isLocation = true;
            resolve('success');
            _this.getProvince();
          },
          fail(err) {
            // console.log(err, 'err');
            _this.isLocation = false;
            resolve('fail');
            _this.getProvince();
            _this.dealerName = '请选择意向经销商';
          }
        });
      });
    },
    getBasePrice() {
      request
        .http({
          url: Api.base_price_detail,
          type: 'GET',
          header: {},
          data: {
            hid: this.carHid
          }
        })
        .then(result => {
          this.basePrice = result.data;
        });
    },
    getProvince() {
      request
        .http({
          url: Api.province_city,
          type: 'GET',
          header: {},
          data: {
            loc_lng: this.loc_lng,
            loc_lat: this.loc_lat,
            car_style_hid: this.carHid
          }
        })
        .then(result => {
          this.newProvinceCityList = result.data.list;
          let _privateList = this.newProvinceCityList;
          let _cityList = _privateList[0].citys;
          this.regionList = [_privateList, _cityList];
          this.province_id = _privateList[0].hid;
          this.city_id = _privateList[0].citys[0].hid;

          if (this.isLocation) {
            this.getDealer();
          }
        });
    },
    regionListChange({ detail }) {
      this.province_id = this.regionList[0][detail.value[0]].hid;
      this.city_id = this.regionList[1][detail.value[1]].hid;

      this.getDealer();
      this.isLocation = true;
    },
    // 列更新事件
    async regionListColumnchange({ detail: { column, value } }) {
      let citylist = [];
      // 省份更新
      if (column === 0) {
        this.newProvinceCityList.forEach((element, index) => {
          if (index === value) {
            citylist = element.citys;
          }
        });
        this.provinceCityIndex = [value, this.provinceCityIndex[1]];
        this.regionList = [this.newProvinceCityList, citylist];
      } else {
        this.provinceCityIndex = [this.provinceCityIndex[0], value];
      }
    },
    // 选择经销商
    selectDealer(val) {
      this.isLocation = true;
      this.dealerList.forEach(item => {
        item.isSelected = val.hid === item.hid ? 1 : 0;
      });
      this.dealerId = val.hid;
      this.dealerName = val.name;
      this.$refs.popup.close();
    },

    // 获取手机号
    onGetPhoneNumbers(e) {
		// console.log(e,11111);
      	if (e.detail.errMsg != 'getPhoneNumber:fail user deny') {
			request
			.http({
				url: Api.decrypt_phone,
				type: 'POST',
				header: {
					token: uni.getStorageSync('token'),
					"app-source": 2,
					"applet-num": 2,
				},
				data: {
				encrypted_data: e.detail.encryptedData,
				iv: e.detail.iv,
				verify_code: e.detail.code
				}
			})
			.then(result => {
				// console.log('--------------------------', result);
				this.isShow = true;
				const { encode_phone, phone_sign } = result.data;
				this.phone = encode_phone;
				this.phone_sign = phone_sign;
				uni.setStorageSync('empower_phone', encode_phone);
				uni.setStorageSync('phone_sign', this.phone_sign);
			});
		}else{
			// console.log('--------------------------', e);
			this.isEmpower = false
		}
    },
	onGetPhoneNumber (e) {
		// console.log(e, '3', e.detail.errNo)
		this.isShow = true
		if(e.detail.errMsg != 'getPhoneNumber:fail user deny') {
			request.http(
			{
				url: Api.decrypt_phone,
				type: 'POST',
				header: {
					// 'content-type': 'application/x-www-form-urlencoded',
					"app-source": 2,
					"applet-num": 2,
					'token':uni.getStorageSync('token')
				},
				data: {
					encrypted_data: e.detail.encryptedData,
					iv: e.detail.iv,
					verify_code: e.detail.code
				},
				}).then(result=>{
					this.phone = result.data.encode_phone
					this.phone_sign = result.data.phone_sign
					uni.setStorageSync('empower_phone', this.phone)
					uni.setStorageSync('phone_sign', this.phone_sign)
					this.formClick(1)
					
				})
		} else {
			// console.log('拒绝')
			this.isEmpower = false
			// this.formClick()
		}
		
	},

    inputChange() {
        
      if (this.phone.length === 11) {
        this.phone_sign = null;
		    this.isShow = false;
      } else if (this.phone.length === 0) {
        this.phone_sign = null;
		    this.isShow = true
      }
    },
    formClick() {
		  this.isEmpower = false
      if (this.provincename === '请选择购车城市') {
        uni.showToast({
          title: '请选择购车城市',
          icon: 'none'
        });
        return;
      }

      if (this.phone === '' || this.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确手机号',
          icon: 'none'
        });
        return;
      }
      if (!this.isShow && this.sms_code === '') {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none'
        });
        return;
      }
      let obj = {
        adid: this.reqArgs.adid,
        creativeid: this.reqArgs.creativeid,
        creativetype: this.reqArgs.creativetype,
        clickid: this.reqArgs.clickid
      };
      request
        .http({
          url: Api.leave_clue,
          type: 'POST',
          header: {
            token: uni.getStorageSync('token'),
			"app-source": 2,
			"applet-num": 2
          },
          data: {
            cate: 1,
            province_id: this.province_id,
            city_id: this.city_id,
            style_hid: this.carHid,
            dea_hid: this.dealerId,
            phone: !this.phone_sign ? this.phone : '',
            sms_code: this.sms_code,
            mount_log_hid: this.mount_log_hid ? this.mount_log_hid : '',
            phone_cate: !this.isShow ? 2 : 1,
            phone_sign: this.phone_sign,
            dy_ad: obj
          }
        }).then(result => {
          deliverClickCallback('form', this.reqArgs);
          this.$refs.modalPopup.open('center');
        }).catch(err => {
        //   console.log(err, '333');
        });
    },

    showModal() {
      if (this.dealerList.length !== 0) {
        this.$refs.popup.open('bottom');
      }
    },
    closeModal() {
      this.$refs.popup.close();
    },

    jumpHome() {
      this.$refs.modalPopup.close();
    },
    getSMS() {
		if (this.phone === '') {
			uni.showToast({
				title: '请输入手机号',
				icon: 'none'
			});
			return;
		}
		request.http({
          url: Api.getCode,
          type: 'POST',
          header: {},
          data: {
            cate: 1,
            phone: this.phone
          }
        }).then(() => {
          this.setTime();
          this.isSMS = true;
        });
    },
    setTime() {
      if (this.countdown === 0) {
        this.countdown = 60;
        clearTimeout(this.timeClock);
        this.isSMS = false;
      } else {
        this.countdown--;
        this.timeClock = setTimeout(() => {
          this.setTime();
        }, 1000);
      }
    },
    getDealer() {
      request.http({
          url: Api.dealer_list,
          type: 'GET',
          header: {},
          data: {
            city_id: this.city_id,
            loc_lng: this.loc_lng,
            loc_lat: this.loc_lat,
            car_style_hid: this.carHid
          }
        }).then(result => {
          result.data.list.forEach((item, index) => {
            item.isSelected = index === 0 ? 1 : 0;
          });
          this.dealerList = result.data.list;
          if (this.dealerList.length > 0) {
            this.dealerName = result.data.list[0].name;
            this.dealerId = result.data.list[0].hid;
          } else {
            this.dealerName = '暂无经销商';
            this.dealerId = '';
          }
        });
    },
    jumpAgreement() {
      uni.navigateTo({
        url: '/subPackage/personal/agreement'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.page {
  width: 100%;
  height: 100vh;
  background: #fff;

  .top {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 43rpx 29rpx 0;
    box-sizing: border-box;
    .img-box {
      display: flex;
      justify-content: center;
      transform: translateX(-10rpx);
      margin-bottom: 28rpx;
      img {
        width: 72rpx;
        height: 72rpx;
        border: 3rpx solid #fff;
        margin-right: -20rpx;
        object-fit: cover;
        border-radius: 50%;
      }
    }
    .num {
      font-weight: 500;
      color: #222526;
      font-size: 33rpx;
      display: flex;
      align-items: center;
      margin-bottom: 21rpx;
      .color-num {
        font-weight: 500;
        color: #3075fe;
        font-size: 43rpx;
        margin: 0 15rpx;
      }
    }
    .tips {
      font-weight: 300;
      color: #222526;
      font-size: 25rpx;
    }
  }

  .car-info {
    width: 100%;
    height: 178rpx;
    background: #fff;
    border-radius: 7rpx;
    display: flex;
    align-items: center;
    padding: 0 29rpx;
    box-sizing: border-box;
    margin-top: 20rpx;
    .left {
      width: 215rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      img {
        width: 199rpx;
        height: 134rpx;
      }
    }

    .middle {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding-left: 20rpx;
      justify-content: center;
      .title {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
        .name {
          font-weight: 500;
          color: #222526;
          font-size: 29rpx;
        }
        .cheap {
          margin-left: 8rpx;
          height: 40rpx;
          padding: 0 13rpx;
          background: rgba(255, 51, 34, 0.1);
          margin-left: 10rpx;
          .cheap-cont {
            font-weight: 500;
            color: #ff3322;
            font-size: 20rpx;
            width: 100%;
            line-height: 40rpx;
          }
        }
      }
      .price {
        font-weight: 400;
        color: #6e7175;
        font-size: 22rpx;
        margin-top: 10rpx;
      }
      .base-price {
        font-weight: 500;
        color: #ff3322;
        font-size: 25rpx;
        margin-top: 15rpx;
      }
    }
    .right {
      img {
        width: 43rpx;
        height: 43rpx;
      }
    }
  }

  .select-item {
    width: 100%;
    padding: 0 29rpx;
    box-sizing: border-box;
    margin-top: -20rpx;
    .item {
      display: flex;
      width: 100%;
      height: 100rpx;
      align-items: center;
      border-bottom: 1rpx solid #dcdde0;
      .left {
        width: 116rpx;
      }
      .left,
      .middle {
        font-weight: 400;
        color: #222526;
        font-size: 29rpx;
      }
      .middle {
        flex: 1;
        margin-left: 57rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .right {
        img {
          width: 43rpx;
          height: 43rpx;
          margin-top: 25rpx;
        }
        .btn {
          font-weight: 400;
          color: #3075fe;
          font-size: 29rpx;
          background: none;
        }
        button::after {
          border: none;
        }
      }
    }
  }
  .btn-box {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: fixed;
    bottom: 60rpx;
    left: 0;
    .btn-price {
      width: 692rpx;
      height: 87rpx;
      background: #3075fe;
      border-radius: 4rpx;
      font-weight: 400;
      color: #fff;
      font-size: 29rpx;
      margin-bottom: 21rpx;
      line-height: 87rpx;
    }
    .tips-text {
      font-weight: 400;
      color: #6e7175;
      font-size: 22rpx;
      display: flex;
    }
  }

  .dea-box {
    width: 100%;
    height: 942rpx;
    overflow-y: auto;
    background: #fff;
    padding: 0 29rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .cancel-title {
      width: 100%;
      display: flex;
      align-items: center;
      padding: 29rpx 0;
      box-sizing: border-box;
      border-bottom: 1rpx solid #dcdde0;

      .cancel {
        font-weight: 400;
        color: #13a1cb;
        font-size: 29rpx;
      }
      .title {
        flex: 1;
        text-align: center;
        font-weight: 500;
        color: #222526;
        font-size: 33rpx;
      }
    }
    .list-box {
      width: 100%;
      overflow-y: auto;
      .list-item {
        width: 100%;
        padding-top: 20rpx;
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        position: relative;
        .icon {
          position: absolute;
          top: 40%;
          right: 20rpx;
          transform: translate(0, -40%);
        }
        .title {
          font-weight: 500;
          color: #222526;
          font-size: 29rpx;
          margin-bottom: 15rpx;
        }
        .address {
          display: flex;
          font-weight: 400;
          font-size: 22rpx;
          color: #6e7175;
          border-bottom: 2rpx solid #dcdde0;
          padding-bottom: 23rpx;
          padding-right: 100rpx;
          .gang {
            margin: 0 10rpx;
          }
          .distance {
            // 预留
          }
        }
      }
    }
  }

  .modal {
    width: 551rpx;
    background: #fff;
    border-radius: 7rpx;
    padding: 28rpx 0 53rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    .title {
      font-weight: 500;
      color: #021615;
      font-size: 33rpx;
      margin-bottom: 28rpx;
    }
    .content {
      font-weight: 400;
      color: #021615;
      font-size: 29rpx;
      margin-bottom: 57rpx;
    }
    .btn {
      width: 196rpx;
      height: 72rpx;
      background: #3075fe;
      border-radius: 4rpx;
      font-weight: 400;
      color: #fff;
      font-size: 27rpx;
      line-height: 72rpx;
      text-align: center;
    }
  }
}
</style>

<style>
button::after {
  border: none;
}
</style>
